package controllers

import (
	"2301a_tv/cache"
	"2301a_tv/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
)

type TvController struct {
	beego.Controller
}

// 添加
func (c *TvController) Add() {
	name := c.GetString("name")
	types := c.GetString("types")
	address := c.GetString("address")
	time := c.GetString("time")
	status := c.GetString("status")
	if name == "" || types == "" || address == "" || time == "" || status == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "参数不能为空",
		}
		c.ServeJSON()
		return
	}

	var tv models.TV
	tv.Name = name
	tv.Types = types
	tv.Address = address
	tv.Time = time
	tv.Status = status
	err := tv.Add()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
	} else {
		tvs, _ := tv.List()
		jsonData, _ := json.Marshal(tvs)
		cache.Rdb.Set(cache.Ctx, "tv", jsonData, 0)
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "添加成功",
		}
		c.ServeJSON()
	}
}

// 展示
func (c *TvController) List() {
	cacheData := cache.Rdb.Get(cache.Ctx, "tv_list").Val()
	var tvs []*models.TV
	if cacheData == "" {
		models.DB.Find(&tvs)
		jsonData, _ := json.Marshal(tvs)
		cache.Rdb.Set(cache.Ctx, "tv_list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &tvs)
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "展示成功",
			"data": tvs,
		}
		c.ServeJSON()
	}
}

// 删除
func (c *TvController) Del() {
	id, _ := c.GetInt("id")
	var tv models.TV
	tv.ID = uint(id)
	err := tv.Del()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
	} else {
		tvs, _ := tv.List()
		jsonData, _ := json.Marshal(tvs)
		cache.Rdb.Set(cache.Ctx, "tv", jsonData, 0)
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "删除成功",
		}
		c.ServeJSON()
	}
}

// 修改
func (c *TvController) Update() {
	var tv models.TV
	id, _ := c.GetInt("id")
	tv.ID = uint(id)
	tv.Name = c.GetString("name")
	tv.Types = c.GetString("types")
	tv.Time = c.GetString("time")
	tv.Address = c.GetString("address")
	tv.Status = c.GetString("status")
	err := tv.Update()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "修改失败",
		}
		c.ServeJSON()
	} else {
		tvs, _ := tv.List()
		jsonData, _ := json.Marshal(tvs)
		cache.Rdb.Set(cache.Ctx, "tv", jsonData, 0)
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "修改成功",
		}
		c.ServeJSON()
	}
}
